#include<iostream>
#include<cstdio>
#include<pthread.h>
#include<string>
#include<vector>
#include<unistd.h>

#define NUM 5

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;

void* SlaverCore(void* args)
{
    const std::string name = static_cast<char*>(args);
    while(true)
    {
        //环境变量一般在加锁、解锁之间使用
        pthread_mutex_lock(&mutex); 
        pthread_cond_wait(&cond, &mutex); //等待条件满足
        std::cout << "当前被唤醒的线程: " << name << std::endl;
        sleep(1);
        pthread_mutex_unlock(&mutex);
    }

}

void* MasterCore(void* args) 
{
    const std::string name = static_cast<char*>(args);
    std::cout << "master running...." << std::endl;
    sleep(2);
    while(true)
    {
        pthread_cond_signal(&cond); //唤醒一个线程
        std::cout << "master唤醒一个线程...." << std::endl;
        sleep(1);
    }
}

void StartSlaver(std::vector<pthread_t>* threads) //创建其他线程
{
    for(int i = 0; i < NUM; i++)
    {
        char* name = new char(64);
        snprintf(name, 64, "slaver-%d", i + 1);

        pthread_t tid;
        int n = pthread_create(&tid, NULL, SlaverCore, name);
        if(n == 0)
            std::cout << "create success: " << name << std::endl;
        threads->push_back(tid);
    }
}

void StartMaster(std::vector<pthread_t>* threads)  //创建主控线程
{
    pthread_t tid;
    int n = pthread_create(&tid, NULL, MasterCore, (void*)"master thread");
    if(n == 0)
        std::cout << "create master thread success!" << std::endl;
    threads->push_back(tid);
}

void  WaitThread(std::vector<pthread_t>* threads) 
{
    for(auto& tid : *threads)
    {
        pthread_join(tid, NULL); 
    }
}

int main()
{
    //验证线程同步机制  一个线程控制其他线程
    std::vector<pthread_t> threads;
    StartMaster(&threads); //主控线程
    StartSlaver(&threads);  //其他线程
    WaitThread(&threads); //线程等待,回收资源,防止造成内存泄漏

    return 0;
}